package com.mishow.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.adapter.CityAdapter;
import com.mishow.adapter.CitySortAdapter;
import com.mishow.bean.AddrItem;
import com.mishow.db.DBhelper;
import com.mishow.log.MyLog;
import com.mishow.sortlistview.PinYin;
import com.mishow.sortlistview.PinyinComparator;
import com.mishow.sortlistview.SideBar;
import com.mishow.sortlistview.SideBar.OnTouchingLetterChangedListener;
import com.mishow.sortlistview.SortModel;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.widget.MyGridView;
/**
 * 
 * 作者：wei.miao <br/>
 * 描述：城市选择
 */
public class CityListActivity extends BaseActivity implements OnClickListener{

    // 标题栏
    private TextView title_tv;
    // 返回按钮
    private TextView btn_back;
    // 拼音首字母排序listview
    private ListView listview;
    // 热门城市
    private MyGridView gridview_hot_city;
    // 汉字拼音首字母适配器
    private CitySortAdapter adapter;
    // 热门城市适配器
    private CityAdapter hot_city_adapter;
    // 热门城市list
    private ArrayList<String> hot_city_list;
    // sortmodel list
    private List<SortModel> sortModels;

    private SideBar sidebar;

    private TextView dialog;
    // 汉字转换成拼音的类
    // 根据拼音来排列ListView里面的数据类
    private PinyinComparator pinyinComparator;


    private ArrayList<AddrItem> citys;

    private DBhelper dBhelper;

    // 热门城市
    private ArrayList<AddrItem> hotCitys;

    private Intent cityintent;     //城市列表传参
    private Intent hotcityintent;  //热门城市列表传参
    
    
    public static void intoActivity(Context context) {

		Intent intent = new Intent(context,CityListActivity.class);
		((Activity)context).startActivityForResult(intent, Constants.CITYLIST_CODE);

	}

    @Override
    protected void initData() {
    	dBhelper = new DBhelper(this,true);
        // 实例化汉字转拼音类
        pinyinComparator = new PinyinComparator();
        hot_city_list = new ArrayList<String>();
        hotCitys = new ArrayList<AddrItem>();

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.location_city);
        title_tv = (TextView) findViewById(R.id.title_tv);
        btn_back = (TextView) findViewById(R.id.btn_back);
        listview = (ListView) findViewById(R.id.listview_city);
        View headView = LayoutInflater.from(this).inflate(R.layout.citylist_headview, null);
        listview.addHeaderView(headView);
        gridview_hot_city = (MyGridView) headView.findViewById(R.id.gridview_hot_city);
        sidebar = (SideBar) findViewById(R.id.sidebar);
        dialog = (TextView) findViewById(R.id.dialog);
        sidebar.setTextView(dialog);
    }

    @Override
    protected void setAttribute() {

        btn_back.setOnClickListener(this);

        doGetHotCity();
        fillPinyin();
        fillHotCity();
        setRightMenuClick();
        setAllCityClick();
        setHotCityItemClick();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                this.finish();
                break;

            default:
                break;
        }

    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<SortModel> filledData() {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        MyLog.d("com.rogrand.kkmy", "filledData() citys = :" + citys.size());
        for (int i = 0; i < citys.size(); i++) {
            //TODO 用于隐藏“S”中重复显示3次的"省直辖县级行政区划"项
            if ("省直辖县级行政区划".equals(citys.get(i).getAddrName())) {
                continue;
            }

            SortModel sortModel = new SortModel();
            sortModel.setName(AndroidUtil.getCityStr(citys.get(i).getAddrName()));
            // 汉字转换成拼音
            String pinyin = PinYin.getPinYin(citys.get(i).getAddrName());
            if (TextUtils.isEmpty(pinyin) || pinyin.length() == 0) {
                continue;
            }
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            sortModel.setAddId(citys.get(i).getAddrId());
            sortModel.setCodeId(citys.get(i).getAddrCode());
            mSortList.add(sortModel);
        }
        return mSortList;
    }

    /**
     * 添加城市拼音排列
     */
    private void fillPinyin() {
        citys = dBhelper.getAllCitys();
        sortModels = filledData();
        // 根据a-z进行排序源数据
        Collections.sort(sortModels, pinyinComparator);
        adapter = new CitySortAdapter(this, sortModels);
        listview.setAdapter(adapter);
    }

    /**
     * 从服务器获取热门城市
     */
    private void doGetHotCity() {
        
    }

    /**
     * 添加热门城市
     */
    private void fillHotCity() {

        hot_city_adapter = new CityAdapter(this, hot_city_list);
        gridview_hot_city.setAdapter(hot_city_adapter);
    }

    /**
     * 设置全部城市下的子项监听
     */
    private void setAllCityClick() {

        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position < 1) {
                    return;
                }
                int cityCode = sortModels.get(position - 1).getCodeId();
                String cityName = sortModels.get(position - 1).getName();
                cityintent = new Intent();
                cityintent.putExtra(Constants.CITY_NAME, cityName);
                cityintent.putExtra(Constants.CITY_CODE, cityCode+"");
                setResult(RESULT_OK, cityintent);
                CityListActivity.this.finish();
            }
        });
    }

    /**
     * 设置右侧触摸监听
     */
    private void setRightMenuClick() {
        sidebar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    listview.setSelection(position);
                }
            }
        });
    }

    /**
     * 设置热门城市下的子项监听
     */
    private void setHotCityItemClick() {

        gridview_hot_city.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String cityName = hotCitys.get(position).getAddrName();
                int cityCode = hotCitys.get(position).getAddrCode();
                hotcityintent = new Intent();
                hotcityintent.putExtra("cityName", cityName);
                hotcityintent.putExtra("cityCode", cityCode);
                setResult(RESULT_OK, hotcityintent);
                CityListActivity.this.finish();
            }
        });
    }

}
